package com.zline.foodraise.wx;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.view.View;

import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.baidu.mobstat.StatService;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXImageObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.zline.foodraise.R;
import com.zline.foodraise.adapter.ShareChannelsAdapter;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.ShareChannel;
import com.zline.foodraise.util.ImageUtil;
import com.zline.foodraise.util.LUtil;

import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.RootContext;
import org.androidannotations.annotations.res.StringRes;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by heshantao on 15/8/11.
 * 微信工具类
 */
@EBean
public class WxShareUtil {
    private static final String LOG_TAG = WxShareUtil.class.getSimpleName();
    @RootContext
    Context cxt;
    //app 与微信交互的接口
    IWXAPI api;
    @Bean
    ShareChannelsAdapter adapter;
    List<ShareChannel> shareList;
    @StringRes(R.string.wechat)
    String weiXin;
    @StringRes(R.string.timeline)
    String weChat;
    //图片分享的图片地址
    String picPath;
    @Bean
    ImageUtil imageUtil;
    //分享渠道0-微信 1-微信朋友圈
    int shareChannel;
    //分享方式，1-链接，2-图片
    int mShareContentType;
    int sharePicWidth = 100;
    @StringRes(R.string.share_title)
    String share_title;
    @StringRes(R.string.share_descript)
    String share_descipt;
    String defaultShareUrl = Constant.SHARE_URL;

    //注册到微信
    public void regToWx() {
        //通过wx工厂产生API 实例
        api = WXAPIFactory.createWXAPI(cxt, Constant.WX_APP_ID, true);
        api.registerApp(Constant.WX_APP_ID);
    }


    //分享图片
    public void sendPicReq() {
        WXImageObject wxImageObject = new WXImageObject();
        wxImageObject.setImagePath(picPath);
        WXMediaMessage msg = new WXMediaMessage();
        msg.title = share_title;
        msg.mediaObject = wxImageObject;
        msg.description = share_descipt;
        LUtil.i(LOG_TAG,"____________执行时间_开始____"+System.currentTimeMillis());
        Bitmap bmp = imageUtil.decodeAndCompressImageByQuality(picPath, 32);
        LUtil.i(LOG_TAG,"____________执行时间_结束____"+System.currentTimeMillis());
        float ratio = imageUtil.getPicLengthWidthRatio(picPath);
        int scaleHeight = (int) (ratio * sharePicWidth);
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, sharePicWidth, scaleHeight, true);
        bmp.recycle();
        msg.thumbData = imageUtil.bitmap2Bytes(thumbBmp);
        bmp.recycle();

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        if (shareChannel == 0) {
            //微信
            req.scene = SendMessageToWX.Req.WXSceneSession;
            StatService.onEvent(cxt, "share_pic_wx_friend", "分享模板图片给微信好友");
        } else if (shareChannel == 1) {
            //朋友圈
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
            StatService.onEvent(cxt, "share_pic_wx_cycle", "分享模板图片给微信朋友圈");
        }
        api.sendReq(req);
    }

    //分享链接
    public void sendUrlReq() {
        WXWebpageObject webpageObject = new WXWebpageObject();
        webpageObject.webpageUrl = defaultShareUrl;
        LUtil.i(LOG_TAG, "________分享链接______" + defaultShareUrl);
        final WXMediaMessage msg = new WXMediaMessage();
        msg.title = share_title;
        msg.mediaObject = webpageObject;
        msg.description = share_descipt;

        ImageLoader imageLoader = ImageLoader.getInstance();
        DisplayImageOptions options = imageUtil.
                getDisplayImageOptions(R.mipmap.ic_launcher,
                        R.mipmap.ic_launcher, R.mipmap.ic_launcher);
        imageLoader.loadImage(picPath, options, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {

            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                if (loadedImage == null) {
                    loadedImage = BitmapFactory.decodeResource(cxt.getResources(), R.mipmap.default_notice);
                }
                Bitmap thumbBmp = Bitmap.createScaledBitmap(loadedImage, 80, 80, true);
                msg.thumbData = imageUtil.bitmap2Bytes(thumbBmp);
                thumbBmp.recycle();

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = msg;
                if (shareChannel == 0) {
                    //微信
                    req.scene = SendMessageToWX.Req.WXSceneSession;
                } else if (shareChannel == 1) {
                    //朋友圈
                    req.scene = SendMessageToWX.Req.WXSceneTimeline;
                }
                api.sendReq(req);

            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {

            }
        });

    }


    //分享内容方式(模板或者链接)
    public void setShareContentType(int shareContentType) {
        this.mShareContentType = shareContentType;
    }

    //分享图片的地址
    public void setSharePicPath(String picPath) {
        this.picPath = picPath;
    }

    //分享渠道，微信、朋友圈
    public void setShareChannel(int channel) {
        this.shareChannel = channel;
    }

    //链接分享时候的标题
    public void setShareTitle(String title) {
        this.share_title = title;
    }

    //链接分享时候的描述
    public void setShareDescipt(String descipt) {
        this.share_descipt = descipt;
    }

    //链接分享时候的url地址
    public void setShareUrl(String url) {
        this.defaultShareUrl = url;
    }


    //初始化分享渠道
    void initShareData() {
        ShareChannel weixinShare = new ShareChannel(R.mipmap.template_share_wechat, weiXin);
        ShareChannel wechatShare = new ShareChannel(R.mipmap.template_share_timeline, weChat);
        shareList = new ArrayList<>();
        shareList.add(weixinShare);
        shareList.add(wechatShare);
        adapter.setData(shareList);

    }

    //打开分享对话框
    public void openShareDialog() {
        initShareData();
        regToWx();
        new MaterialDialog.Builder(cxt)
                .title(R.string.share)
                .titleGravity(GravityEnum.CENTER)
                .adapter(adapter, new MaterialDialog.ListCallback() {
                    @Override
                    public void onSelection(MaterialDialog materialDialog,
                                            View view, int position, CharSequence charSequence) {
                        shareChannel = position;
                        if (mShareContentType == Constant.PIC_SHARE_TYPE) {
                            sendPicReq();
                        } else if (mShareContentType == Constant.URL_SHARE_TYPE) {
                            sendUrlReq();
                        }
                        materialDialog.dismiss();
                    }
                }).show();

    }
}
